package com.hearwego;

import java.util.Calendar;

import com.hearwego.TabMisGastos.LoagGastos;
import com.hearwego.utilities.GastosAdapter;
import com.hearwego.utilities.HWGSQLiteHelper;
import com.hearwego.utilities.Utilities;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;


public class TabMisGastosDetalle extends BaseFragment {
	Bundle ext;
	Button inicio, agregar_lista;
	ListView lista;
	private ProgressDialog progressDialog;
	String[] idgasto, idlista, listaname, monto, fecha ;
//	ArrayAdapter<String> adapter;
	String idlistaextras;
	GastosAdapter adapter;
	
	public TabMisGastosDetalle(Bundle extras){
		ext = extras;
	}
	
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view       =   inflater.inflate(R.layout.tab_mis_gastos_detalle, container, false);
//        + mActivity.getIntent().getExtras().getInt("valor")
        Log.i("idlista", ""+ext.getString("idlista"));
        idlistaextras = ""+ext.getString("idlista");
        lista = (ListView) view.findViewById(R.id.list_gastos);

        //Para verificar notas existentes
        new LoagGastosDetalle().execute("");
        
        inicio = (Button) view.findViewById(R.id.bt_inicio);
        agregar_lista = (Button) view.findViewById(R.id.bt_gasto);
        inicio.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				mActivity.onBackPressed();
			}
		});
        agregar_lista.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				addGasto();
			}
		});

        
        return view;
    }
    
    
    public void deleteGasto(final int i){
    	//Abrimos la base de datos 'DBUsuarios' en modo escritura
        HWGSQLiteHelper usdbh =new HWGSQLiteHelper(mActivity, "DBHWG", null, 1);
        final SQLiteDatabase db = usdbh.getWritableDatabase();
        
        AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
		builder.setMessage(R.string._borrar_nota_)
		       .setCancelable(false)
		       .setPositiveButton(R.string.s_, new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
				        if(db != null)
				        {
				        	//Eliminar un registro
//				        	db.execSQL("DELETE FROM Lista WHERE idlista="+i);
				        	db.execSQL("DELETE FROM Gastos WHERE idgasto="+i);

							Toast.makeText(mActivity.getApplicationContext(), R.string.nota_eliminada, Toast.LENGTH_SHORT).show();
							dialog.dismiss();
				            //Cerramos la base de datos
				            db.close();
				            new LoagGastosDetalle().execute("");
				            //Async
				        }
		           }
		       })
		       .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
		           public void onClick(DialogInterface dialog, int id) {
		        	   dialog.cancel();
		           }
		       });
		AlertDialog alertDialog = builder.create();
		alertDialog.show();
        
    }
    
    
    public void addGasto(){
    	//Abrimos la base de datos 'DBUsuarios' en modo escritura
        HWGSQLiteHelper usdbh =new HWGSQLiteHelper(mActivity, "DBHWG", null, 1);
        final SQLiteDatabase db = usdbh.getWritableDatabase();
        
        final Dialog dialog = new Dialog(mActivity);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(R.layout.dialog_add_gasto);
		Button bt_cancelar = (Button) dialog.findViewById(R.id.bt_cancelar);
		Button bt_aceptar = (Button) dialog.findViewById(R.id.bt_aceptar);
		final EditText et_descr = (EditText) dialog.findViewById(R.id.et_descr);
		final EditText et_monto = (EditText) dialog.findViewById(R.id.et_monto);

		
		bt_cancelar.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});
		
		bt_aceptar.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if((et_descr.getText().toString().equals(""))||(et_monto.getText().toString().equals(""))){
					Toast.makeText(mActivity.getApplicationContext(), "Campos vacíos", Toast.LENGTH_SHORT).show();
				}else{
					 //Si hemos abierto correctamente la base de datos
			        if(db != null)
			        {
			        	Calendar c = Calendar.getInstance(); 
			        	
			        	int mes = c.get(Calendar.MONTH)+1;
			        	String fechahora = ""+c.get(Calendar.DAY_OF_MONTH)+"/"+mes+"/"+c.get(Calendar.YEAR)+
			        			"  "+c.get(Calendar.HOUR_OF_DAY)+":"+c.get(Calendar.MINUTE)+":"+c.get(Calendar.SECOND);
			        	
			        	db.execSQL("INSERT INTO Gastos (idgasto, idlista, gasto, cantidad, fechahora) " +
		                           "VALUES (null, " + idlistaextras +", '" + et_descr.getText().toString() +
		                           "', '" + et_monto.getText().toString() +"', '" + fechahora+"')");
						Toast.makeText(mActivity.getApplicationContext(), "Gasto agregada", Toast.LENGTH_SHORT).show();
						dialog.dismiss();
			            //Cerramos la base de datos
			            db.close();
			            new LoagGastosDetalle().execute("");
			            //Async
			        }
					
				}
				
			}
		});
		
		dialog.show();
    }
    
    public class LoagGastosDetalle extends AsyncTask<String, String, String>{
    	int zeroGastos = -1;
    	
    	@Override
    		protected void onPreExecute() {
    			super.onPreExecute();
    			progressDialog = ProgressDialog.show(mActivity, "",
    					"Cargando...", true, true, new OnCancelListener() {
    						
    						@Override
    						public void onCancel(DialogInterface arg0) {
    							mActivity.onBackPressed();
    						}
    			});
    		}
    	
    	
		@Override
		protected String doInBackground(String... params) {
			HWGSQLiteHelper usdbh =new HWGSQLiteHelper(mActivity, "DBHWG", null, 1);
	        final SQLiteDatabase db = usdbh.getWritableDatabase();
	        int i = 0;
	        if(db != null)
	        {
	        	String[] args = new String[]{idlistaextras};
	        	Cursor c = db.rawQuery("SELECT * FROM Gastos WHERE idlista=?", args);
	        	idgasto = new String[c.getCount()];
	        	idlista = new String[c.getCount()];
	        	listaname = new String[c.getCount()];
	        	monto = new String[c.getCount()];
	        	fecha = new String[c.getCount()];
	        	//Nos aseguramos de que existe al menos un registro
	        	if (c.moveToFirst()) {
	        		zeroGastos = 1;
	        	     //Recorremos el cursor hasta que no haya más registros
	        	     do {
	        	    	 Log.i("DO", "WHILE "+i);
	        	    	 idgasto[i] = c.getString(0);
	        	    	 idlista[i] = c.getString(1);
	        	    	 listaname[i] = c.getString(2);
	        	    	 monto[i] = c.getString(3);
	        	    	 fecha[i] = c.getString(4);
	        	          i++;
	        	     } while(c.moveToNext());
	        	     
	        	     
	        	}else{
	        		zeroGastos = 0;
	        	}
	        	

	            //Cerramos la base de datos
	            db.close();
	            
	            //Async
	        }
	        
	        
			return null;
		}
		
		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if(zeroGastos == 1){
				for(int i=0; i<idlista.length; i++){
					Log.i("Arreglos", "idgasto "+idgasto[i]+"idlista "+idlista[i]+" listaname "+listaname[i]+
							"monto "+monto[i]+"fecha "+fecha[i]);
				}
				
				adapter = new GastosAdapter(mActivity,idgasto, idlista, listaname, monto, fecha);
				lista.setAdapter(adapter);
				lista.setOnItemClickListener(new OnItemClickListener() {

					@Override
					public void onItemClick(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {
						deleteGasto(Integer.parseInt(idgasto[arg2]));
						
					}
				});
				
				
			}else if(zeroGastos == 0){
				lista.setAdapter(null);
				Toast.makeText(mActivity.getApplicationContext(), "No hay gastos agregadas", Toast.LENGTH_SHORT).show();
			}

			
			progressDialog.dismiss();
			
			
		}
    	
    }
    


        

}
